﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Xml;

namespace Douban.Api.Infrastructure
{
    public class EntryLoader
    {
        private IDataSourcePool _dataSourcePool;

        private EntryLoader(IDataSourcePool dataSourcePool)
        {
            _dataSourcePool = dataSourcePool;
        }

        public void Load(EntryItem entry)
        {
            if (entry.IsLoaded) return;

            PropertyInfo idProperty = entry.GetType().GetProperties()
                .SingleOrDefault(p => p.IsDefined(typeof(IdAttribute), true));
            
            if(idProperty == null) return;

            string id = (string)idProperty.GetValue(entry, null);

            Stream stream = _dataSourcePool
                .GetDataSource(id, entry.GetType()).Source;

            XmlDocument doc = new XmlDocument();
            doc.Load(stream);

            entry.Initialize(doc.DocumentElement);
            entry.Resolve();

            entry.IsLoaded = true;
        }

        public static EntryLoader Create()
        {
            return Create(null);
        }

        public static EntryLoader Create(IDataSourcePool dataSourcePool)
        {
            if (dataSourcePool == null)
                throw new ArgumentNullException("dataSourcePool");

            return new EntryLoader(dataSourcePool);
        }
    }
}
